package com.threefish.common.config;

import com.threefish.common.annotation.ResponseJsonBody;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2018/9/11
 */
public class NutzJsonReturnHandler implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseJsonBody.class) ||
                returnType.hasMethodAnnotation(ResponseJsonBody.class));
    }

    @Override
    public void handleReturnValue(Object returnData, MethodParameter returnType, ModelAndViewContainer container, NativeWebRequest request) throws Exception {
        container.setRequestHandled(true);
        JsonFormat format = JsonFormat.compact();
        HttpServletResponse response = request.getNativeResponse(HttpServletResponse.class);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        if (returnType.hasMethodAnnotation(ResponseJsonBody.class)) {
            ResponseJsonBody annotation = returnType.getMethodAnnotation(ResponseJsonBody.class);
            format.setNullAsEmtry(annotation.nullAsEmtry());
            format.setActived(annotation.actived());
            format.setLocked(annotation.locked());
            format.setDateFormat(annotation.dateFormat());
        }
        response.getWriter().write(Json.toJson(returnData, format));
    }
}
